<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/8/19
 * Time: 20:32
 */

class MY_Model extends CI_Model
{
    protected $table = null;  //表名
    public $primary_key = "id"; //主键名称 默认 id
    const DEFAULT_MAX_LIMIT = 100;//默认最大限制查询条数
    protected $start_time = 0;
    protected $debug = false; //是否开启debug 显示耗时和SQL语句
    protected $many_to_one=[];//n:1  e.g  ['user_id'=>["user","author"]]  有外键user_id 对应到 user Ioc对象名  新增字段叫author
    protected $one_to_many=[]; //1:n [["user_icon","user_id","icons"]]  对应很多图标的 Ioc对象 被外键的字段名  新增字段名称 icons
    protected $fields = [];

    //初始化
    public function __construct()
    {
        if($this->debug)
        {
            $this->start_time = $this->getMillisecond();
        }
        parent::__construct();
        $this->load->database();
        if($this->fields)
        {
            $fields_str = implode(",",$this->fields);
            $this->db->select($fields_str);
        }

    }

    //添加数据
    public  function insert($add_data)
    {
      $execute_res = $this->db->insert($this->table,$add_data);
      if($execute_res)
      {
          return $this->db->insert_id();
      }
      else
      {
          return false;
      }
    }

     //删除数据
    public  function delete($delete_where,$limit=1)
    {
        $delete_res = $this->db->limit($limit)->delete($this->table,$delete_where);
        if($delete_res)
        {
           if($this->db->affected_rows()!=0)
           {
               return $this->db->affected_rows();
           }
           else{
               return false;
           }
        }else
            return false;
    }

    //根据id删除数据
    public function deleteById($id)
    {
        $delete_where = [$this->primary_key=>$id];
        return $this->delete($delete_where);
    }

    //修改数据
    public function update($update_data,$update_where,$limit=1)
    {
       $update_res = $this->db->limit($limit)->update($this->table,$update_data,$update_where);
       if($update_res)
       {
           if($this->db->affected_rows()!=0)
           {
               return $this->db->affected_rows();
           }
           else{
               return false;
           }
       }else
       {
           return false;
       }
    }

    //根据id修改数据
    public function updateById($data,$id)
    {
        $update_where = [$this->primary_key=>$id];
        return $this->update($data,$update_where);
    }

    //  直接获取一张表的所有记录数  但是都有最大limit限制
    public  function getTableAllResults($limit=self::DEFAULT_MAX_LIMIT,$offset=0)
    {
       $res_obj = $this->db->get($this->table,$limit);
       return $res_obj->result_array();
    }

    // select * from table  where id = ...根据id获取数据
    public  function getById($id)
    {
       $res_arr =  $this->db->get_where($this->table,[$this->primary_key=>$id],1);
       return $res_arr->row_array();
    }

    //获取一张表的所有记录数
    public function getTableAllRows()
    {
        return $this->db->count_all($this->table);
    }

    //获取时间毫秒数
    protected function getMillisecond()
    {
        $time = microtime(true)*1000;
        $time = floor($time);
        return $time;
    }

    //自定义条件查询  查询总行数还是总的结果集合
    public function getWhere($where,$get_rows=false,$limit=self::DEFAULT_MAX_LIMIT,$offset=0)
    {
        if($get_rows)
        {
            return $this->db->where($where)->count_all_results($this->table);
        }else{
            return $this->db->get_where($this->table,$where,$limit,$offset)->result_array();
        }
    }

    //where in查询
    public function getWhereIn($filed_name,$arr_in,$limit=self::DEFAULT_MAX_LIMIT,$offset=0)
    {
        if(empty($arr_in))  //where in  查询特别注意空数组的情况  否则报错  in ()
        {
            return [];
        }else{
            return $this->db->where_in($filed_name,$arr_in)->get($this->table,$limit,$offset)->result_array();
        }

    }

    //n:1  获取数据
    public function getById_manyToOne($id)
    {
        $my_data = null;
        foreach ($this->many_to_one as $foreign_key_name=>$info)
        {
           $my_data =  $this->db->get_where($this->table,[$this->primary_key=>$id],1,0)->row_array();
           if(!empty($my_data))
           {
               $foreign_id = $my_data[$foreign_key_name];
               unset($my_data[$foreign_key_name]);
               $model = IoC()->$info[0];
               $other_data = $model->getById($foreign_id);
               $my_data[$info[1]] = $other_data;
           }
        }
        return $my_data;
    }

    //1:n 获取数据
    public function getById_oneToMany($id,$limit=self::DEFAULT_MAX_LIMIT,$offset=0)
    {
        $my_data = null;
        foreach ($this->one_to_many as $primary_key=>$info)
        {
            $my_data = $this->getById($id);
            if(!empty($my_data))
            {
                $table_model = IoC()->$info[0];
                $filed_name = $info[1];
                $results = $table_model->getWhere([$filed_name=>$my_data[$this->primary_key]],false,$limit,$offset);
                $new_field_name= $info[2];
                $my_data[$new_field_name] = $results;
            }
        }
        return $my_data;
    }

    //析构函数
    public function __destruct()
    {
        if($this->debug)
        {
            $end_time = $this->getMillisecond();
            $use_time = $end_time-$this->start_time;
            $sql_cmd = $this->db->last_query();
            echo "[--SQL--]:$sql_cmd".PHP_EOL;
            echo "[--USE TIME--] :".$use_time.PHP_EOL;
        }
    }
}
